<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="归属地" prop="belongingPlaceList" >
            <el-cascader v-model="queryParams.belongingPlaceList" :options="optionsnative_place" clearable/>
          </el-form-item>
          <el-form-item label="场地名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入场地名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
<!--          <el-form-item label="负责人" prop="username">-->
<!--            <el-input v-model="queryParams.username" placeholder="请输入负责人" clearable style="width: 240px"-->
<!--                      @keyup.enter="handleQuery"/>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="负责人电话" prop="phone" label-width="100">-->
<!--            <el-input v-model="queryParams.phone" placeholder="请输入负责人电话" clearable style="width: 240px"-->
<!--                      @keyup.enter="handleQuery"/>-->
<!--          </el-form-item>-->
          <el-form-item label="场地状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择场地状态" clearable>
              <el-option
                  v-for="dict in position_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="场地类型" prop="positionType">
            <el-select v-model="queryParams.positionType" placeholder="请选择场地类型" clearable>
              <el-option
                  v-for="dict in position_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:position:add']">新增
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="positionList" border>
        <el-table-column type="index" width="55" align="center" fixed="left"/>
        <el-table-column label="场地ID" align="center" prop="positionId" v-if="false"/>
        <el-table-column label="场地名称" align="center" prop="name" fixed="left"/>
        <el-table-column label="场地描述" align="center" prop="describe"/>
        <el-table-column label="归属地" align="center" prop="belongingPlaceStr" show-overflow-tooltip width="200"/>
        <el-table-column label="场地地址" align="center" prop="location" show-overflow-tooltip width="150"/>
        <el-table-column label="代理商" align="center" prop="agentUserName" width="100"/>
        <el-table-column label="代理商分润比例" align="center" prop="agentRate" width="120" :formatter="agentRateFormatter"/>
        <el-table-column label="管理员" align="center" prop="manageUserName" width="100"/>
        <el-table-column label="管理员分润比例" align="center" prop="manageRate" width="120" :formatter="manageRateFormatter"/>
        <el-table-column label="立即分账" align="center" prop="openSpilt" :formatter="openSpilteFormatter"/>
        <el-table-column label="分账账户" align="center" prop="openid" width="120"/>
        <el-table-column label="分账比例" align="center" prop="spiltRate" width="100" :formatter="spiltRateFormatter"/>
        <el-table-column label="财务负责人" align="center" prop="financeUserName" width="150"/>
        <el-table-column label="设备维护员" align="center" prop="deviceUserName" width="120"/>
        <!--        <el-table-column label="负责人" align="center" prop="username" width="150"/>-->
        <!--        <el-table-column label="负责人电话" align="center" prop="phone" width="120"/>-->
        <el-table-column label="经度" align="center" prop="longitude" width="100"/>
        <el-table-column label="纬度" align="center" prop="latitude" width="100"/>
        <el-table-column label="营业时间" align="center" prop="workTime" width="160"/>
        <el-table-column label="场地状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="position_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="订单统计单价" align="center" prop="statisticsPrice" width="120"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['device:position:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['device:position:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改场地信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="positionFormRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="场地名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场地名称" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="场地描述" prop="describe">
          <el-input v-model="form.describe" placeholder="请输入场地描述" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="场地地址" prop="location">
          <el-input v-model="form.location" placeholder="请输入场地地址" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="归属地" prop="belongingPlaceList" >
          <el-cascader v-model="form.belongingPlaceList" :options="optionsnative_place" clearable/>
        </el-form-item>
        <el-form-item label="代理商" prop="agentUserId">
          <el-select v-model="form.agentUserId" filterable placeholder="请选代理商" @change="handleUserChange">
            <el-option
                v-for="item in getUserListByRoleCode('agent_role')"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                :disabled="item.status === 0"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="代理商分润比例(%)" prop="agentRate">
          <el-input-number v-model="form.agentRate" placeholder="分润比例" :precision="0" min="0" max="100"/>
        </el-form-item>

        <el-form-item label="场地管理员" prop="manageUserId">
          <el-select v-model="form.manageUserId" filterable placeholder="请选管理员" @change="handleUserChange">
            <el-option
                v-for="item in getUserListByRoleCode('position_role')"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                :disabled="item.status === 0"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="管理员分润比例(%)" prop="manageRate">
          <el-input-number v-model="form.manageRate" placeholder="分润比例" :precision="0" min="0" max="100"/>
        </el-form-item>

        <el-form-item label="立即分账" prop="openSpilt">
          <el-switch
            v-model="form.openSpilt"
            class="mb-2"
            active-text="开启"
            inactive-text="关闭"
            active-value="open"
            inactive-value="close"
            @change="handleOpenSpiltChange"
          />
        </el-form-item>
        <el-form-item label="分账账户(openId)" prop="openid" v-if="form.openSpilt==='open'">
          <el-input v-model="form.openid" placeholder="分账账户" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="分账比例(%)" prop="spiltRate" v-if="form.openSpilt==='open'">
          <el-input-number v-model="form.spiltRate" placeholder="分账比例" :precision="0" min="0" max="100"/>
        </el-form-item>

        <el-form-item label="财务人员" prop="financeUserId">
          <el-select v-model="form.financeUserId" filterable placeholder="请选财务人员" @change="handleUserChange">
            <el-option
              v-for="item in getUserListByRoleCode('finance_role')"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                :disabled="item.status === 0"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备维护人员" prop="deviceUserId">
          <el-select v-model="form.deviceUserId" placeholder="请选设备维护人员" @change="handleUserChange">
            <el-option
              v-for="item in getUserListByRoleCode('maintain_role')"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                :disabled="item.status === 0"
            ></el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="负责人" prop="username">-->
        <!--          <el-select v-model="form.user" placeholder="请选择场地负责人" @change="handleUserChange">-->
        <!--            <el-option-->
        <!--              v-for="dict in userList"-->
        <!--              :key="dict.userName"-->
        <!--              :label="'用户: '+dict.userName +',部门: '+dict.dept.deptName+',手机: '+ dict.phonenumber"-->
        <!--              :value="dict"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="经度" prop="longitude">
          <el-input type="number" v-model="form.longitude" placeholder="请输入经度" maxlength="15" show-word-limit/>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input type="number" v-model="form.latitude" placeholder="请输入纬度" maxlength="15" show-word-limit/>
        </el-form-item>
        <el-form-item label="营业时间" prop="workTime">
          <el-input v-model="form.workTime" placeholder="请输入营业时间" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="场地状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择场地状态">
            <el-option
                v-for="dict in position_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="订单统计单价" prop="statisticsPrice">
          <el-input-number v-model="form.statisticsPrice" placeholder="订单统计单价" style="width: 100%" :precision="0" min="0" max="100"/>
        </el-form-item>

        <el-form-item label="是否显示公众号二维码" prop="isShowMp">
          <el-switch
            v-model="form.isShowMp"
            class="mb-2"
            active-text="显示"
            inactive-text="隐藏"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="绑定公众号" prop="bindMpAppId">
          <el-select v-model="form.bindMpAppId" filterable placeholder="请选择公众号" @change="handleUserChange">
            <el-option
              v-for="item in mpInfos"
              :key="item.appId"
              :label="item.name"
              :value="item.appId"
              :disabled="item.status !== 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="50" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Position" lang="ts">
import {listPosition, getPosition, delPosition, addPosition, updatePosition} from '@/api/device/position';
import {PositionVO, PositionQuery, PositionForm} from '@/api/device/position/types';
import {allUser} from "@/api/system/user";
import {listWechatMpInfo} from "@/api/device/wechatMpInfo"
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText, } from "element-china-area-data";
import {computed} from "vue";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  position_status,
  position_type,
  grid_spec
} = toRefs<any>(proxy?.useDict('position_status', 'position_type', 'grid_spec'));

const optionsnative_place = regionData
const positionList = ref<PositionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const positionFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const feeConfigData = [];

const initFormData: PositionForm = {
  positionId: undefined,
  name: undefined,
  describe: undefined,
  location: undefined,
  belongingPlaceList: undefined,
  belongingPlace: undefined,
  belongingPlaceStr: undefined,
  username: undefined,
  agentUserId: undefined,
  agentRate: undefined,
  manageUserId: undefined,
  manageRate: undefined,
  spiltRate: undefined,
  openid: undefined,
  openSpilt: undefined,

  financeUserId: undefined,
  deviceUserId: undefined,
  user: undefined,
  phone: undefined,
  longitude: undefined,
  latitude: undefined,
  workTime: undefined,
  qrCode: undefined,
  bindMpAppId:undefined,
  isShowMp:undefined,
  status: undefined,
  remark: undefined,
}
const data = reactive<PageData<PositionForm, PositionQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'create_time',
    isAsc: 'desc',
    name: undefined,
    belongingPlaceList: undefined,
    belongingPlace: undefined,
    describe: undefined,
    location: undefined,
    username: undefined,
    phone: undefined,
    longitude: undefined,
    latitude: undefined,
    workTime: undefined,
    qrCode: undefined,
    bindMpAppId:undefined,
    isShowMp:undefined,
    status: undefined,
    params: {}
  },
  userList: [],
  mpInfos:[],
  rules: {
    positionId: [
      {required: true, message: "场地ID不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "场地名称不能为空", trigger: "blur"}
    ],
    describe: [
      {required: true, message: "场地描述不能为空", trigger: "blur"}
    ],
    location: [
      {required: true, message: "场地地址不能为空", trigger: "blur"}
    ],
    agentUserId: [
      {required: true, message: "代理商不能为空", trigger: "blur"}
    ],
    agentRate: [
      {required: true, message: "代理商分润比例不能为空", trigger: "blur"}
    ],
    manageUserId: [
      {required: true, message: "管理员不能为空", trigger: "blur"}
    ],
    manageRate: [
      {required: true, message: "管理员分润比例不能为空", trigger: "blur"}
    ],
    username: [
      {required: true, message: "负责人不能为空", trigger: "blur"}
    ],
    phone: [
      {required: true, message: "负责人电话不能为空", trigger: "blur"}
    ],
    longitude: [
      {required: true, message: "经度不能为空", trigger: "blur"}
    ],
    latitude: [
      {required: true, message: "纬度不能为空", trigger: "blur"}
    ],
    workTime: [
      {required: true, message: "营业时间不能为空", trigger: "blur"}
    ],
    qrCode: [
      {required: true, message: "场地二维码地址不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "设备状态：online 营业,wait 待营业 , discard 已废弃不能为空", trigger: "change"}
    ],
    openSpilt: [
      {required: true, message: "分账开关不能为空", trigger: "blur"}
    ],
    spiltRate: [
      {required: true, message: "分账比例不能为空", trigger: "blur"}
    ],
    openid: [
      {required: true, message: "分账账户不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules, userList,mpInfos} = toRefs(data);


function agentRateFormatter(row){
  return row.agentRate + '%';
}
function manageRateFormatter(row){
  return row.manageRate + '%';
}

function spiltRateFormatter(row){
  return row.spiltRate + '%';
}

function openSpilteFormatter(row){
  if (row.openSpilt ==="open"){
    return "开启";
  }else {
    return "关闭";
  }
}

/**
 * 选择场地联动设备
 * @param val
 */
function handleUserChange(val: string) {
  form.value.username = val.userName;
  form.value.phone = val.phonenumber;
}

function handleOpenSpiltChange() {
  form.value.openid = undefined;
  form.value.spiltRate = undefined;
}


const getUserList = async () => {
  loading.value = true;
  const res = await allUser();
  loading.value = false;
  userList.value = res.rows;
}

const getMpInfos=async ()=>{
  loading.value = true;
  const res = await listWechatMpInfo();
  loading.value = false;
  mpInfos.value = res.rows;
}

/** 查询场地信息列表 */
const getList = async () => {
  loading.value = true;
  if (queryParams.value.belongingPlaceList){
    queryParams.value.belongingPlace = queryParams.value.belongingPlaceList.join(',');
  }
  const res = await listPosition(queryParams.value);
  positionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  positionFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: PositionVO[]) => {
  ids.value = selection.map(item => item.positionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  getUserList();
  getMpInfos();
  dialog.title = "添加场地信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PositionVO) => {
  reset();
  const _positionId = row?.positionId || ids.value[0]
  const res = await getPosition(_positionId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  getUserList();
  getMpInfos();
  dialog.title = "修改场地信息";
  let username = row.userName;
  let user = userList.value.find(item => item.username === username);
  form.value.user = user
}

/** 提交按钮 */
const submitForm = () => {
  positionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.belongingPlaceList){
        form.value.belongingPlace = form.value.belongingPlaceList.join(',');
        form.value.belongingPlaceStr = codeToText[form.value.belongingPlaceList[0]]+"/"+codeToText[form.value.belongingPlaceList[1]]+"/"+codeToText[form.value.belongingPlaceList[2]];
      }
      if (form.value.positionId) {
        await updatePosition(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addPosition(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: PositionVO) => {
  const _positionIds = row?.positionId || ids.value;
  await proxy?.$modal.confirm('是否确认删除场地为"' + row?.name + '"的数据项？').finally(() => loading.value = false);
  await delPosition(_positionIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/position/export', {
    ...queryParams.value
  }, `position_${new Date().getTime()}.xlsx`)
}

const getUserListByRoleCode=computed(()=>(roleKey:any)=>{
  let list=(userList.value||[]).filter((item:any)=>{
    return (item.roles||[]).filter((role:any)=>{
      return role.roleKey===roleKey;
    }).length>0;
  });
  return list;
});

onMounted(() => {
  getList();
  getUserList();
});
</script>
